package com.wngbms;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class _03_06 {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();

        SumFuture sumFuture = new SumFuture();
        new Thread(sumFuture).start();

        System.out.println("异步计算结果为：" + sumFuture.getSum());
        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");
    }

    public static class SumFuture implements Runnable {
        Integer sum;

        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();

        public int getSum() {
            lock.lock();
            try {
                while (sum == null) {
                    condition.await();
                }
                return sum;
            } catch (InterruptedException e) {
                e.printStackTrace();
                return -1;
            } finally {
                lock.unlock();
            }
        }

        public void setSum(int sum) {
            lock.lock();
            try {
                this.sum = sum;
                condition.signal();
            } finally {
                lock.unlock();
            }
        }

        @Override
        public void run() {
            setSum(_03_06.sum());
        }
    }

    private static int sum() {
        return fibo(45);
    }

    private static int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }
}
